﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Linq;
using System.Text;
using System;
using com.guojin.mj.net.message.game;

public class ChangeInfo : MonoBehaviour
{
    public Button Ret, Send, Sex, heads, closePhoto, takephoto, savephoto,queDing,quXiao;
    public Image SexImage;
    public RawImage head;
    public InputField Name;
    private bool Nv = true;
    public int sex = 1;
    private string acct;//应该是传手机号的，现在传过来的id
    private string pass;
    private string userId;//用户id
    private string lastName;//用户上一个名字
    public GameObject photo, BG_image,changeNamePay;
    public string headsBase64 = "a";
    // Use this for initialization

    #region 初始化给头像给名字
    void Awake()
    {
        SetText(Name, GameData.GetInstance().userName);
        lastName = GameData.GetInstance().userName;

        Debug.Log(GameData.GetInstance().avatar);
        DownloadHeadTexture(head, GameData.GetInstance().avatar);
           //LoginAndShare
    }

    protected void SetText(InputField text, string str)                                                 //设置text文本
    {
        try
        {
            if (text == null)
            {
                Debug.Log(string.Format("为{0}设置显示文本{1}，{0}为null", text.gameObject, str));
            }
            else
            {
                if (string.IsNullOrEmpty(str))
                {
                    text.text = string.Empty;
                }
                else
                {
                    text.text = TooL.strGetNewline(str);
                }
            }
        }
        catch (System.Exception ex)
        {
            Debug.Log(string.Format("为{0}设置显示文本{1}引发报错", text.gameObject, str));
            throw ex;
        }
    }

    protected void DownloadHeadTexture(RawImage texture, string url)            //下载头像图片
    {
        //texture = null;
#if WX_SDK
        if (url != null)
        {
            //用户头像，最后一个数值代表正方形头像大小（有0、46、64、96、132数值可选，0代表640*640正方形头像），用户没有头像时该项为空
            //url = url.Substring(0, url.Length - 1);
            //url += "132";    
            StartCoroutine(DownloadTexture(texture, url));
        }
        else
        {
            Debug.Log("下载头像Texture收到的url为空！");
        }
#else
        url = URLConst.DefaultUserHeadUrl;
        StartCoroutine(DownloadTexture(texture, url));
#endif
    }

    private IEnumerator DownloadTexture(RawImage texture, string url)
    {
        WWW www = new WWW(url);
        yield return www;
        texture.texture = www.texture;

        Texture2D tex2d = texture.texture as Texture2D;
        Debug.Log("转换tex2d完成");
        tex2d = ScaleTexture(tex2d, 300, 300);
        Debug.Log("缩放完成");
        byte[] bytes = tex2d.EncodeToPNG();
         headsBase64 = Convert.ToBase64String(bytes);

    }
    private Texture2D ScaleTexture(Texture2D source, int targetWidth, int targetHeight)
    {
        Texture2D result = new Texture2D(targetWidth, targetHeight, source.format, false);
        for (int i = 0; i < result.height; i++)
        {
            for (int j = 0; j < result.width; j++)
            {
                Color newColor = source.GetPixelBilinear((float)j / (float)result.width, (float)i / (float)result.height);
                result.SetPixel(j, i, newColor);
            }
        }
        result.Apply();
        return result;
    }
    #endregion

    void Start()
    {
        Sex.onClick.AddListener(ChangeSex);//设置性别
        Send.onClick.AddListener(SendName);//点击提交
        heads.onClick.AddListener(ShowPhoto);//打开头像上传方式界面
        closePhoto.onClick.AddListener(ClosePhoto);//关闭头像上传方式界面
        takephoto.onClick.AddListener(TakePhoto);//打开相册
        savephoto.onClick.AddListener(TakePhotoSave);//打开相机
        Ret.onClick.AddListener(Close);//关闭本界面
        queDing.onClick.AddListener(QueDing);//点击确定（修改了名字，保存）
        quXiao.onClick.AddListener(QuXiao);//取消修改名字
        Screen.autorotateToPortrait = true;
        Screen.autorotateToPortraitUpsideDown = true;
        Screen.autorotateToLandscapeRight = false;
        Screen.autorotateToLandscapeLeft = false;
    }

    //设置账号 sc     验证码pa
    //public void SetAcc(string sc, string pa)
    //{
    //    acct = sc;
    //    pass = pa;
    //}

    //设置用户id
    public void SetAcc(string userID)
    {
        userId = userID;
    }
    //设置性别
    void ChangeSex()
    {
        if (Nv)
        {
            sex = 2;
            SexImage.sprite = Resources.Load<Sprite>("UI/性别_女");
            Nv = false;
        }
        else
        {
            sex = 1;
            SexImage.sprite = Resources.Load<Sprite>("UI/性别_男");
            Nv = true;
        }
    }
    //显示添加图片按钮
    void ShowPhoto()
    {
        photo.SetActive(true);
    }
    //关闭添加图片按钮
    void ClosePhoto()
    {
        photo.SetActive(false);
    }
    //调用插件功能，打开手机相册
    void TakePhoto()
    {
        LoginAndShare.Controller.OpenPhoto(0);
    }
    //1打开相机
    void TakePhotoSave()
    {
        LoginAndShare.Controller.OpenPhoto(1);
    }
    //关闭按钮      删除本界面
    void Close()
    {
        Destroy(this.gameObject);
    }

    //点击取消按钮
    void QuXiao()
    {
        changeNamePay.SetActive(false);
    }
    //点击确定按钮  发送保存界面消息按钮删除本界面。带扣钱//todo(发送方法没写）
    void QueDing()
    {
        string param = "{ \"type\":\"img\",\"data\":\"data:image/png;base64," + headsBase64 + "\"}";
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("data", param);
        string result = HttpPostData(ServerAdress, dic);
        Debug.Log("服务器返回地址:" + result);
        Close();
    }
 

    private string ServerAdress = "http://121.40.90.67:8092/up";
    //这个是收到1.25   4类型代表语音
    public int msgType = 4;

    //发送录音文件字节流，将返回字节流广播出去（（提交按钮）发送界面）
    public void SendName()//点击提交
    {
        if (Name.text == null || Name.text == "")
        {
            TooL.WenXinTiSi("昵称不能为空");
            return;
        }
        if (headsBase64 == "a" || headsBase64 == "" || headsBase64 == null)
        {
            TooL.WenXinTiSi("头像不能为空");
            return;
        }
        if (Name.text != lastName)//名字修改了显示名字修改弹窗
        {
            changeNamePay.SetActive(true);
        }

        string param = "{ \"type\":\"img\",\"data\":\"data:image/png;base64," + headsBase64 + "\"}";
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("data", param);
        string result = HttpPostData(ServerAdress, dic);
        Debug.Log("服务器返回地址:" + result);
        //BG_image.SetActive(true);
        //MessageManager.GetInstance().Send7148(result, Name.text, sex, acct, pass);//发送注册信息，
    }
    //发送录音字节流 收到服务器返回网址
    public string HttpPostData(string url, Dictionary<string, string> dic)
    {
        var result = string.Empty;
        //#region 添加Post 参数  
        StringBuilder builder = new StringBuilder();
        int i = 0;
        foreach (var item in dic)
        {
            if (i > 0)
                builder.Append("&");
            builder.AppendFormat("{0}={1}", item.Key, item.Value);
            i++;
        }

        byte[] postData = Encoding.UTF8.GetBytes(builder.ToString());
        // 设置提交的相关参数 

        System.Net.HttpWebRequest request = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
        Encoding myEncoding = Encoding.UTF8;
        request.Method = "POST";
        request.KeepAlive = false;
        request.AllowAutoRedirect = true;
        request.ContentType = "application/x-www-form-urlencoded";
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
        request.ContentLength = postData.Length;
        request.Timeout = 3000;

        // 提交请求数据 
        System.IO.Stream outputStream = request.GetRequestStream();
        outputStream.Write(postData, 0, postData.Length);
        outputStream.Close();

        System.Net.HttpWebResponse response;
        Stream responseStream;
        StreamReader reader;
        string srcString;
        response = request.GetResponse() as System.Net.HttpWebResponse;
        responseStream = response.GetResponseStream();
        reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
        srcString = reader.ReadToEnd();
        result = srcString;   //返回值赋值
        reader.Close();
        Debug.Log("获取HttpPostData服务器返回Version" + result);
        return result;
    }
}
